<template>
  <div class="login-page">
    <el-card>
      <template #header>黑马面经运营后台</template>

      <el-form ref="form" :model="form" :rules="rules" autocomplete="off">
        <el-form-item label="用户名：" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>

        <el-form-item label="密码：" prop="password">
          <el-input placeholder="请输入密码：" v-model="form.password" />
        </el-form-item>


        <el-form-item class="tc">
          <el-button @click="login" type="primary">登 录</el-button>

          <el-button @click="reset">重 置</el-button>

        </el-form-item>

      </el-form>

    </el-card>

  </div>

</template>

<script>
export default {
  name: 'login-page',
  data() {
    return {
      form: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: ['blur', 'change'] },
          { min: 5, max: 11, message: '长度在 5 到 11 个字符', trigger: ['blur', 'change'] }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: ['blur', 'change'] },
          { pattern: /^\w{5,11}$/, message: '请输入 5 到 10 位的密码', trigger: ['blur', 'change'] }
        ]
      }

      // \d 数字 0-9
      // \w 字母数字下划线
      // {m,n} 前面的字符，可以出现 m次 ~ n次
    }
  },

  methods: {
    reset() {
      this.$refs.form.resetFields()
    },
    async login() {
      try {
        // 调用validate()方法，检查表单是否合法
        const valid = await this.$refs.form.validate()
        console.log("表单合法", valid)
        // 调用vuex的action loginAction完成登录请求并存储token到vuex中(内存)
        await this.$store.dispatch("user/loginAction", this.form);
        // 登录成功，跳转到首页
        this.$message.success("登录成功");
        this.$router.push("/article");
      } catch (e) {
        console.log("表单不合法", e)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.login-page {
  min-height: 100vh;
  background: url(@/assets/login-bg.svg) no-repeat center / cover;
  display: flex;
  align-items: center;
  justify-content: center;

  .el-card {
    width: 420px;

    ::v-deep .el-card__header {
      height: 80px;
      line-height: 40px;
      background: rgba(114, 124, 245, 1);
      text-align: center;
      color: #fff;
      font-size: 18px;
    }
  }

  .el-form {
    padding: 0 20px;
  }

  .tc {
    text-align: center;
  }
}
</style>
